unit UnitMainForm;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
  Menus, DBGrids, LR_Class, pqconnection, sqldb, db;

type
  config = record
    host : string[50];
    db : string[50];
    user : string[20];
    passwd : string[20];
  end;

type

  { TMainForm }

  TMainForm = class(TForm)
    Datasource1: TDatasource;
    DBGrid1: TDBGrid;
    frReport1: TfrReport;
    MainMenu1: TMainMenu;
    MenuItem1: TMenuItem;
    MenuItem10: TMenuItem;
    MenuItem11: TMenuItem;
    MenuItem12: TMenuItem;
    MenuItem13: TMenuItem;
    MenuItem2: TMenuItem;
    MenuItem3: TMenuItem;
    MenuItem4: TMenuItem;
    MenuItem5: TMenuItem;
    MenuItem6: TMenuItem;
    MenuItem7: TMenuItem;
    MenuItem8: TMenuItem;
    MenuItem9: TMenuItem;
    PQConnection1: TPQConnection;
    SQLQuery1: TSQLQuery;
    SQLTransaction1: TSQLTransaction;
    StatusBar1: TStatusBar;
    procedure DBGrid1CellClick(Column: TColumn);
    procedure FormShow();
    procedure frReport1GetValue(const ParName: String; var ParValue: Variant);
    procedure MenuItem12Click(Sender: TObject);
    procedure MenuItem13Click(Sender: TObject);
    procedure MenuItem2Click(Sender: TObject);
    procedure MenuItem3Click(Sender: TObject);
    procedure MenuItem4Click(Sender: TObject);
    procedure MenuItem6Click(Sender: TObject);
    procedure MenuItem7Click(Sender: TObject);
    procedure MenuItem8Click(Sender: TObject);
    procedure ordenar_grid();
    function generar_ean8(nro_cliente : string; codigo_control : string) : string;
  private
    apellido : string;
    nombre : string;
    tipodoc : string;
    nrodoc : string;
    nrocliente : string;
    vencimiento : string;
    codigo_control : string;
    ean8 : string;
  public
    { public declarations }
  end; 

var
  MainForm: TMainForm;
  archivo : file of config;
  registro : config;

implementation

uses
  UnitAccesoDatos, UnitAltaCliente;

{ TMainForm }

function TMainForm.generar_ean8(nro_cliente : string; codigo_control : string) : string;
type
  arreglo = array[1..8] of string;

var
  largo_nro_cliente : integer;
  i : integer;
  pos : arreglo;
  total_ean8 : integer;
  total_ean8_str : string;
  ultimo_digito : string;
  decena_superior : integer;
  digito_verificador : integer;

begin
  largo_nro_cliente := Length(nro_cliente);

  for i := 1 to (5 - largo_nro_cliente) do
    nro_cliente := '0' + nro_cliente;

  nro_cliente := codigo_control + nro_cliente;

  for i := 1 to 7 do
  begin
    pos[i] := copy(nro_cliente, i, 1);
  end;

  total_ean8 := strToint(pos[1]) * 3 + strToint(pos[3]) * 3 + strToint(pos[5]) * 3 + strToint(pos[7]) * 3
    + strToint(pos[2]) + strToint(pos[4]) + strToint(pos[6]);

  total_ean8_str := intTostr(total_ean8);

  ultimo_digito := copy(total_ean8_str, length(total_ean8_str), 1);

  if strToInt(ultimo_digito) > 0 then
    decena_superior := total_ean8 + (10 - strToint(ultimo_digito))
  else
    decena_superior := total_ean8;

  digito_verificador := decena_superior - total_ean8;

  pos[8] := intTostr(digito_verificador);

  for i := 1 to 4 do
  begin
    if pos[i] = '0' then
      pos[i] := 'A'
    else
    if pos[i] = '1' then
      pos[i] := 'B'
    else
    if pos[i] = '2' then
      pos[i] := 'C'
    else
    if pos[i] = '3' then
      pos[i] := 'D'
    else
    if pos[i] = '4' then
      pos[i] := 'E'
    else
    if pos[i] = '5' then
      pos[i] := 'F'
    else
    if pos[i] = '6' then
      pos[i] := 'G'
    else
    if pos[i] = '7' then
      pos[i] := 'H'
    else
    if pos[i] = '8' then
      pos[i] := 'I'
    else
    if pos[i] = '9' then
      pos[i] := 'J';
  end;

  for i := 5 to 8 do
  begin
    if pos[i] = '0' then
      pos[i] := 'a'
    else
    if pos[i] = '1' then
      pos[i] := 'b'
    else
    if pos[i] = '2' then
      pos[i] := 'c'
    else
    if pos[i] = '3' then
      pos[i] := 'd'
    else
    if pos[i] = '4' then
      pos[i] := 'e'
    else
    if pos[i] = '5' then
      pos[i] := 'f'
    else
    if pos[i] = '6' then
      pos[i] := 'g'
    else
    if pos[i] = '7' then
      pos[i] := 'h'
    else
    if pos[i] = '8' then
      pos[i] := 'i'
    else
    if pos[i] = '9' then
      pos[i] := 'j';
  end;

  generar_ean8 := ':' + pos[1] + pos[2] + pos[3] + pos[4] + '*' + pos[5] + pos[6] + pos[7] + pos[8] + '+';
end;

procedure TMainForm.ordenar_grid();
var
  QueryString : string;
begin
  if SQLQuery1.Active = true then
    SQLQuery1.Close;

  SQLQuery1.SQL.Text := 'select cln_cdg, cln_apellido, cln_nombre, cln_tipodoc, '
    + 'cln_nro_doc, cln_nro_cliente from cliente where cln_apellido '
    + 'ilike ''%' + apellido + '%'' order by cln_apellido';

  SQLQuery1.Open;

  DBGrid1.Columns[0].Title.Caption := 'Código';
  DBGrid1.Columns[1].Title.Caption := 'Apellido';
  DBGrid1.Columns[2].Title.Caption := 'Nombre';
  DBGrid1.Columns[3].Title.Caption := 'Tipo Documento';
  DBGrid1.Columns[4].Title.Caption := 'Nro de Documento';
  DBGrid1.Columns[5].Title.Caption := 'Nro de Cliente';

  DBGrid1.Columns[0].Width := 55;
  DBGrid1.Columns[1].Width := 200;
  DBGrid1.Columns[2].Width := 200;
  DBGrid1.Columns[3].Width := 100;
  DBGrid1.Columns[4].Width := 200;
  DBGrid1.Columns[5].Width := 200;

  DBGrid1.Columns[0].Alignment := taLeftJustify;
  DBGrid1.Columns[4].Alignment := taLeftJustify;
end;

procedure TMainForm.FormShow();
begin
  if PQConnection1.Connected = False then
  begin
    if FileExists('configuracion.dat') = False then
    begin
      ShowMessage('SISTEMA SIN CONFIGURAR!');
      FormAccesoDatos.ShowModal;
    end;

    AssignFile(archivo, 'configuracion.dat');
    Reset(archivo);
    Read(archivo, registro);
    CloseFile(archivo);

    PQConnection1.HostName := registro.host;
    PQConnection1.DatabaseName := registro.db;
    PQConnection1.Username := registro.user;
    PQConnection1.Password := registro.passwd;

    PQConnection1.Connected := True;
  end;
  StatusBar1.Panels[0].Text := 'Conectado!   Servidor: ' + registro.host
    + '   DB: ' + registro.db;

  apellido := '%';
  ordenar_grid;
end;

procedure TMainForm.frReport1GetValue(const ParName: String;
  var ParValue: Variant);
begin
  if ParName = 'apellido' then
    ParValue := uppercase(apellido);

  if ParName = 'nombre' then
    ParValue := uppercase(nombre);

  if ParName = 'tipodoc' then
    ParValue := tipodoc;

  if ParName = 'nrodoc' then
    ParValue := nrodoc;

  if ParName = 'nrocliente' then
    ParValue := ean8;

  if ParName = 'vencimiento' then
    ParValue := vencimiento;
end;

procedure TMainForm.DBGrid1CellClick(Column: TColumn);
begin
  if SQLQuery1.RecordCount > 0 then
  begin
    codigo_control := InputBox('Codigo de Control', 'Ingrese el código de control:', '');
    vencimiento := InputBox('Vencimiento de la Tarjeta', 'Ingrese fecha de vencimiento de la tarjeta (mm/aaaa):', '');
    apellido := SQLQuery1.FieldByName('cln_apellido').AsString;
    nombre := SQLQuery1.FieldByName('cln_nombre').AsString;
    tipodoc := SQLQuery1.FieldByName('cln_tipodoc').AsString;
    nrodoc := SQLQuery1.FieldByName('cln_nro_doc').AsString;
    nrocliente := SQLQuery1.FieldByName('cln_nro_cliente').AsString;
    ean8 := generar_ean8(nrocliente, codigo_control);

    frReport1.LoadFromFile('tarjeta.lrf');
    frReport1.ShowReport;
  end;
end;

procedure TMainForm.MenuItem12Click(Sender: TObject);
begin
  apellido := InputBox('Búsqueda de Cliente',
    'Ingrese parte del apellido del cliente:', '');

  if apellido <> '' then
    ordenar_grid
  else
    apellido := '%';
end;

procedure TMainForm.MenuItem13Click(Sender: TObject);
begin
  apellido := '%';
  ordenar_grid;
end;

procedure TMainForm.MenuItem2Click(Sender: TObject);
var
  old_host : string;
  old_db : string;
  old_user : string;
  old_passwd : string;

begin
  old_host := registro.host;
  old_db := registro.db;
  old_user := registro.user;
  old_passwd := registro.passwd;

  FormAccesoDatos.ShowModal;

  if (old_host <> FormAccesoDatos.Edit1.Text)
    or (old_db <> FormAccesoDatos.Edit2.Text)
    or (old_user <> FormAccesoDatos.Edit3.Text)
    or (old_passwd <> FormAccesoDatos.Edit4.Text) then
    ShowMessage('REINICIE EL PROGRAMA PARA HACER EFECTIVOS LOS CAMBIOS');

  FormShow;
end;

procedure TMainForm.MenuItem3Click(Sender: TObject);
begin
  frReport1.Clear;
  frReport1.LoadFromFile('tarjeta.lrf');
  frReport1.DesignReport;
end;

procedure TMainForm.MenuItem4Click(Sender: TObject);
begin
  Close;
end;

procedure TMainForm.MenuItem6Click(Sender: TObject);
begin
  FormAltaCliente.ShowModal;
  ordenar_grid;
end;

procedure TMainForm.MenuItem7Click(Sender: TObject);
var
  QueryString : string;
  codigo : string;

begin
  codigo := InputBox('Baja de Cliente', 'Ingrese el código de cliente:', '');

  if codigo <> '' then
  begin
    QueryString := 'delete from cliente where cln_cdg = ' + codigo;

    PQConnection1.ExecuteDirect('BEGIN WORK');
    PQConnection1.ExecuteDirect(QueryString);
    PQConnection1.ExecuteDirect('COMMIT WORK');

    ShowMessage('BAJA EXITOSA');

    FormShow;
  end;
end;

procedure TMainForm.MenuItem8Click(Sender: TObject);
begin
  ShowMessage('Click en el cliente!');
end;

{$R *.lfm}

end.

